package com.hui.service.impl;

import com.hui.enums.Sex;
import com.hui.mapper.UsersMapper;
import com.hui.pojo.bo.UserBo;
import com.hui.pojo.Users;
import com.hui.service.UserService;
import com.hui.utils.DateUtil;
import com.hui.utils.MD5Utils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    private static final String USER_FACE = "";

    @Autowired
    private Sid sid;

    @Autowired
    public UsersMapper usersMapper;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {
        Example userExample = new Example(Users.class);
        Example.Criteria UserCriteria = userExample.createCriteria();
        UserCriteria.andEqualTo("username",username);
        Users users = usersMapper.selectOneByExample(userExample);
        return users==null?false:true;

    }

    /**
     * 创建一个用户
     * @param userBo 主要传输关键数据流
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users createUser(UserBo userBo) {
        String userId = sid.nextShort();   //获取一个全局唯一ID

        Users users = new Users();
        users.setId(userId);
        users.setUsername(userBo.getUsername());
        try {
            users.setPassword(MD5Utils.getMD5Str(userBo.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //默认用户昵称同用户名
        users.setNickname(userBo.getUsername());
        users.setFace(USER_FACE);
        //未设置默认
        users.setBirthday(DateUtil.stringToDate("1900-01-01"));
        //使用枚举类
        users.setSex(Sex.secret.type);
        users.setCreatedTime(new Date());
        users.setUpdatedTime(new Date());

        usersMapper.insert(users);

        return  users;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserForLogin(String username,String password) {
        Example userExample = new Example(Users.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andEqualTo("username",username);
        userCriteria.andEqualTo("password",password);

        Users resultOne = usersMapper.selectOneByExample(userExample);
        return resultOne;
    }
}
